package com.iwinding.ladygg.ui.act.device;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.iwinding.ladygg.bluetooth.bean.BleDevice;
import com.iwinding.ladygg.bluetooth.impblekit.BleKitManager;
import com.iwinding.ladygg.bluetooth.impblekit.ICaneBleApi;
import com.iwinding.ladygg.runtimepermissions.PermissionsManager;
import com.iwinding.ladygg.runtimepermissions.PermissionsResultAction;
import com.iwinding.ladygg.ui.act.BaseActivity;
import com.iwinding.ladygg.ui.adapter.CommonAdapter;
import com.iwinding.ladygg.ui.adapter.ViewHolder2;
import com.iwinding.ladygg.ui.view.ProDialogCreator;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.utils.DoubleClickUtil;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import static com.iwinding.ladygg.bluetooth.MyGattAttributes.SERVICE_NAME;

/**
 * 设备连接
 * Created by hezhiyong on 2017/3/14.
 */

public class DeviceActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    //Debugging
    private static final String TAG = DeviceActivity.class.getSimpleName();

    public static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;

    private AVLoadingIndicatorView mAVsearch;
    private TextView mTvsearch;
    private View mLayDevice;
    private AVLoadingIndicatorView mAVDevice;
    private ListView lstv_devList;

    private List<BleDevice> deviceList;
    private CommonAdapter<BleDevice> deviceAdapter;

    private MyBle icaneMyBle = null;

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_device;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != icaneMyBle)
            icaneMyBle.distory();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    void initView() {
        setBackTxtResId(R.string.bottom_tab_myself);
        setTitleResId(R.string.icane_my_connet);

        mAVsearch = (AVLoadingIndicatorView) findViewById(R.id.search_avload);
        mTvsearch = (TextView) findViewById(R.id.icane_txt_search);
        mLayDevice = findViewById(R.id.lay_device);
        mAVDevice = (AVLoadingIndicatorView) findViewById(R.id.device_avload);
        lstv_devList = (ListView) findViewById(R.id.device_listview);

    }

    void initData() {
        mTvsearch.setText(getString(R.string.icane_search_device, ""));

        ProDialogCreator.getInstance().initContext(this);
        initAdapter();
        lstv_devList.setOnItemClickListener(this);

        initDeviceNum();
//        BleManager.getInstance().initBle(this);
//        BleManager.getInstance().register(iHandler);
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                //TODO 初始化蓝牙
                initAndScan();
            }

            @Override
            public void onDenied(String permission) {
                Toast.makeText(mContext, permission, Toast.LENGTH_SHORT).show();
//                Toast.makeText(mContext, "位置访问权限被拒绝将无法搜索到ble设备", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void initAdapter() {
        deviceList = new ArrayList<>();
        deviceAdapter = new CommonAdapter<BleDevice>(
                this, R.layout.icane_adapter_item_device, deviceList) {
            @Override
            public void convert(ViewHolder2 holder, final BleDevice device) {
                holder.setText(R.id.txtv_name, TextUtils.isEmpty(device.deviceName) ? "" : device.deviceName);
                holder.setText(R.id.txtv_address, TextUtils.isEmpty(device.deviceAddress) ? "" : device.deviceAddress);
                holder.setText(R.id.txtv_connState, device.isConnect ?
                        getResources().getString(R.string.state_connected) :
                        getResources().getString(R.string.state_disconnected));
                holder.setText(R.id.btn_connect, device.isConnect ?
                        getResources().getString(R.string.disconnected) :
                        getResources().getString(R.string.connected));
                holder.getView(R.id.btn_connect).setVisibility(View.GONE);
            }
        };
        lstv_devList.setAdapter(deviceAdapter);
    }

    private void initAndScan() {
        icaneMyBle = new MyBle(this, deviceList, deviceAdapter);
        icaneMyBle.initBle();
    }

    /**
     * 初始化设备
     */
    void initDeviceNum() {
        mTvsearch.setText(getString(R.string.icane_search_device, String.valueOf(0)));
        mAVsearch.smoothToShow();
        mAVDevice.smoothToShow();
        //初始化
        deviceList.clear();
    }

    /**
     * 设置设备
     *
     * @param num
     */
    void setDeviceNum(int num) {
        mTvsearch.setText(getString(R.string.icane_search_device, String.valueOf(num)));
        mLayDevice.setVisibility(View.VISIBLE);
        mAVsearch.smoothToHide();
        mAVDevice.smoothToHide();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Ble数据回调
        boolean isClick = DoubleClickUtil.getInstance().isCaneClick();
        if (!isClick) {
            return;
        }
        final BleDevice device = deviceAdapter.getItem(position);
        if (device.isConnect) {
            Intent intent = new Intent(mContext.getApplicationContext(), DeviceDetailActivity.class);
            intent.putExtra(DeviceDetailActivity.UUID, TextUtils.isEmpty(device.uuid) ? SERVICE_NAME : device.uuid);
            intent.putExtra(DeviceDetailActivity.NAME, device.deviceName);
            intent.putExtra(DeviceDetailActivity.RSSI, BleKitManager.getInstance().readRssi());
            //如果是ICane则传输音量过去
            if (ICaneBleApi.getInstance().isHandshake())
                intent.putExtra(DeviceDetailActivity.VOLUME, ICaneBleApi.getInstance().getVolume());
            mContext.startActivity(intent);
        } else {
            //TODO 连接蓝牙
            icaneMyBle.connetBle(device);
        }

    }


}
